package com.maiyuren.mdict_flutter_plugin;

import com.knziha.plod.dictionary.mdict;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.os.Build;

public class MdictLib {

    private MdictLib() {};

    private static MdictLib _instance = new MdictLib();
    public static MdictLib getInstance() {
        return _instance;
    }
    private Map<String, mdict> _dicts = new HashMap<>();

    private mdict getDict(String path, boolean createNewIfNotExist) {
        mdict d = _dicts.get(path);
        if (d == null) {
            if (createNewIfNotExist) {
                try {
                    d = new mdict(path);
                    _dicts.put(path, d);
                } catch (Exception ex) {

                }
            }
        }

         return d;
    }

    public String getName(String path) {
        mdict md = getDict(path, true);
        if (md == null) return "";
        return md.getHeaderTag().get("Title");
    }

    public String lookup(String path, String word) {
        try {
            mdict md = getDict(path, true);
            if (md == null) return "";
            try {
                int index = Integer.parseInt(word);
                if (index >= 1 && index <= size(path)) {
                    String html_contents = md.getRecordAt(index - 1);
                    return html_contents;
                }
            } catch (Exception e) {

            }

            int search_result = md.lookUp(word, true);//true means to match strictly
            if(search_result>=0){
                String html_contents = md.getRecordAt(search_result);
                return html_contents;
                // String entry_name = md.getEntryAt(search_result);
            }
        }catch (Exception ex) {
            return "";
        }
        return "";
    }

    public byte[] getResource(String path, String url) {
        try {
            mdict md = getDict(path, true);
            if (md == null) return null;

            InputStream stream = md.getResourceByKey(url);//true means to match strictly


            if (stream != null) {
                byte[] buf = new byte[stream.available()];
                int len = stream.read(buf);
                if (len == buf.length) {
                    return buf;
                }
                return null;
            }
        }catch (Exception ex) {
        }
        return null;
    }

    public int size(String path) {
        mdict dict = getDict(path, false);
        if (dict != null) return (int)dict.getNumberEntries();
        return 0;
    }

    public void release(String path) {
        _dicts.put(path, null);
    }

    public void suggest(String path, String word, int maxCount, List<String> result) {
    }
}
